package org.example.demo3;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author Gong.Yang
 * 传统IO和直接内存IO速度区别演示
 */
@Slf4j
public class DemoIOCompare {
    static final String input = "E:\\image图库.7z"; //389MB
    static final String out = "E:\\沿途风景\\image图库.7z";
    static final int _1Mb = 1024 * 1024;

    public static void main(String[] args) {
        heapMemory();   //0.7s
        allocateMemory();//0.4s
    }

    @SneakyThrows
    private static void allocateMemory() {
        FileChannel inputChannel = new FileInputStream(input).getChannel();
        FileChannel outChannel = new FileOutputStream(out).getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(_1Mb);
        log.info("【allocateMemory】 开始复制");
        while (true) {
            int read = inputChannel.read(byteBuffer);
            if (read == -1) {
                break;
            }
            byteBuffer.flip();
            outChannel.write(byteBuffer);
            byteBuffer.clear();
        }
        log.info("【allocateMemory】 复制完成");
        inputChannel.close();
        outChannel.close();
    }

    @SneakyThrows
    private static void heapMemory() {
        FileInputStream inputStream = new FileInputStream(input);
        FileOutputStream fileOutputStream = new FileOutputStream(out);
        byte[] heapMemory = new byte[_1Mb];
        log.info("【heapMemory】 开始复制");
        while (true) {
            int len = inputStream.read(heapMemory);
            if (len == -1) {
                break;
            }
            fileOutputStream.write(heapMemory, 0, len);

        }
        log.info("【heapMemory】 复制完成");
        fileOutputStream.close();
        inputStream.close();
        ;
    }
}
